import axios from "axios";
import { ElMessage } from "element-plus";

const baseURL = "http://localhost:8080";

//创建axios实例
const axiosInstance = axios.create({
    baseURL: baseURL
});

//请求拦截器--请求前的处理
axiosInstance.interceptors.request.use(
    (config) => {
    //请求发送前的处理
    return config;
}, (error) => {
    //请求发生错误的处理
    Promise.reject(error);
});

//请求拦截器--响应后的处理
axiosInstance.interceptors.response.use(
    (response) => {
        return response.data;
    },
    (error) => {
        ElMessage({message: error.response.data.msg, duration: 2000, type: 'error', center: true});
        return Promise.reject(error);//防止代码往下走
    }
);

export const get = <ResponseData>(uri:string,params?:object):Promise<ResponseData> => {
    return axiosInstance.get(uri,{params});
}

export const postForm = <ResponseData>(uri:string,data?:object):Promise<ResponseData> => {
    const config = {
        headers: {"Content-Type": "application/x-www-form-urlencoded; charset=UTF-8"}
    };
    return axiosInstance.post(uri,data,config);
}

export const postData = <ResponseData>(uri:string,data?:object):Promise<ResponseData> => {
    const config = {
        headers: {"Content-Type": "application/json;charset=UTF-8"}
    };
    return axiosInstance.post(uri,JSON.stringify(data),config);
}
